package com.mlz.mlzmall.ui.activity.act.personal;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.google.gson.Gson;
import com.mlz.mlzmall.R;
import com.mlz.mlzmall.bean.GetProductToExchangeResponseid;
import com.mlz.mlzmall.bean.ResponseExchangeInterg;
import com.mlz.mlzmall.bean.ResponseWechatAppPay;
import com.mlz.mlzmall.ui.activity.act.address.postCodeToPCD;
import com.mlz.mlzmall.ui.activity.act.base.BaseActivity;
import com.mlz.mlzmall.ui.activity.act.main.MyApplication;
import com.mlz.mlzmall.ui.activity.act.order.ExchangePaySuccess;
import com.mlz.mlzmall.ui.dialog.AddCartPopupWindow;
import com.mlz.mlzmall.ui.inter.NetResponses;
import com.mlz.mlzmall.ui.utils.mlz.AliPayResult;
import com.mlz.mlzmall.ui.utils.mlz.ConfigInfo;
import com.mlz.mlzmall.ui.utils.mlz.Constans;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.AppManager;
import com.mlz.mlzmall.ui.utils.util.LogUtils;
import com.mlz.mlzmall.ui.utils.util.SharedUtils;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * describe :
 * Created by Pm on 2016/5/30.
 * PackageName com.mlz.mlzmall.ui.activity.act.personal.
 * ProjectName mlzmall_android.
 */

public class ConfirmExchangeActivity extends BaseActivity implements NetResponses {
    private RelativeLayout iv_back_exchange_ok;
    private int ProductToExchangeId;
    private TextView integration_point;
    private TextView tv_freight_price;
    private TextView tv_exchange_names;//地址名字
    private TextView tv_number;//地址电话号码
    private TextView tv_address;
    private CheckBox cb_wechatpay;
    private CheckBox cb_apipay;

    // 确认兑换 提交按钮
    Button btn_rear_commit;

    // 修改地址用
    String fullname;
    String shippingTelephone;

    String address;
    String postcode;
    String AddressId;
    String price;

    //订单号
    private String orderCode;
    //微信支付布局
    private RelativeLayout rl_weix;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String result = (String) msg.obj;
            AliPayResult result2 = new AliPayResult(result);
            result2.getResult();
            if ("支付成功".equals(result2.getResult())) {
//                Intent intent = new Intent(OrderPayment.this, ExchangePaySuccess.class);
//                intent.putExtra("title", result2.getResult());
//                intent.putExtra("content", result2.getResult());
//                startActivity(intent);
//                finish();
            }

        }
    };
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comfirm_exchange);
        AppManager.getAppManager().addActivity(this);
        initView();
        initListener();
        initData();
    }

    private void initData() {
        ProductToExchangeId = Integer.parseInt(String.valueOf(SharedUtils.get(ConfirmExchangeActivity.this,"ProductToExchangeId",0)));

        initGetDataFromIntent();
        //获取积分和price
        getPriceAndIntegral();
    }

    private void initListener() {

        cb_wechatpay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {//点击微信切换支付宝
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cb_apipay.setChecked(false);
                }
            }
        });
        cb_apipay.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {//点击支付宝切换微信
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    cb_wechatpay.setChecked(false);
                }
            }
        });
        iv_back_exchange_ok.setOnClickListener(this);
        btn_rear_commit.setOnClickListener(this);

    }

    private void initView() {
        integration_point = (TextView) findViewById(R.id.integration_point);
        tv_freight_price = (TextView) findViewById(R.id.tv_freight_price);
        tv_exchange_names = (TextView) findViewById(R.id.tv_exchange_names);//地址名字
        tv_number = (TextView) findViewById(R.id.tv_number);//地址电话号码
        tv_address = (TextView) findViewById(R.id.tv_address);
        btn_rear_commit = (Button) findViewById(R.id.btn_rear_commit);

        //获取CheckBox实例
        cb_wechatpay = (CheckBox) findViewById(R.id.cb_wechatpay);
        cb_apipay = (CheckBox) findViewById(R.id.cb_apipay);
        //设置Checkbox的状态,true 为选中,false为不选中
        cb_wechatpay.setChecked(true);
        iv_back_exchange_ok = (RelativeLayout) findViewById(R.id.iv_back_exchange_ok);

        //
        rl_weix = (RelativeLayout) findViewById(R.id.rl_weix);
        if (WXAPIFactory.createWXAPI(ConfirmExchangeActivity.this, ConfigInfo.APP_ID).isWXAppInstalled()) {
            rl_weix.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 上个界面传过来的数据
     */
    private void initGetDataFromIntent() {
        //获取ProductToExchangeId
        editAddress();

    }
    private void editAddress() {
        // 接受地址信息
        Intent intent = this.getIntent();
        fullname = intent.getStringExtra("FullName");
        shippingTelephone = intent.getStringExtra("Telephone");
        address = intent.getStringExtra("Address");
        postcode = intent.getStringExtra("Postcode");
        AddressId = String.valueOf(intent.getIntExtra("AddressId",0));

        //获取省市区
        postCodeToPCD ppp=new postCodeToPCD(ConfirmExchangeActivity.this);//获取省市县
        String code=String.valueOf(intent.getIntExtra("RegionCode",0));
        String province=ppp.province(code+"");
        String city=ppp.city(code+"");
        String area=ppp.district(code+"");

        Log.i("info", "AddressId-->><<" + AddressId);
        LogUtils.d("AddressId-->><<"+AddressId);
        // 姓名
        tv_exchange_names.setText(fullname);
        //详细地址
        tv_address.setText("地址："+province+city+area+"\t\t"+address);
        // 联系方式
        tv_number.setText(shippingTelephone);


    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.iv_back_exchange_ok:
                finish();
                break;
            case R.id.btn_rear_commit:
                // 提交兑换积分 并支付
                startActivity(new Intent(ConfirmExchangeActivity.this, IntegralPaySuccessActivity.class));
                finish();
                commitAndPay();
                break;
            default:
                break;
        }
    }
    /**
     * 获取商品所需积分和price
     */
    public void getPriceAndIntegral()
    {
        tag = "ConfirmExchange_getPAI";
        JSONObject jsonObject = new JSONObject(getMall());
       // JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, "http://app.mlzmall.com/api/point/exchange/productToExchangeDetail", jsonObject, new Response.Listener<JSONObject>() {
  //      JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, "http://app.mlzMall.com/api/point/exchange/productToExchangeDetail?productToExchangeId="+ProductToExchangeId, null, new Response.Listener<JSONObject>() {
            JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.GET, URL.EXCHANGE.PRODUCTTOEXCHANGDETAIL+"?productToExchangeId="+ProductToExchangeId, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d("获取商品所需积分和price："+jsonObject.toString());
                Gson gson = new Gson();
                GetProductToExchangeResponseid bean = gson.fromJson(jsonObject.toString(),GetProductToExchangeResponseid.class);
                if(bean.getData()!=null)
                {
                    integration_point.setText(bean.getData().getPointsAmount()+"");//积分数
                    tv_freight_price.setText(bean.getData().getFreight()+"");
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }
    private Map<String, String> getMall() {
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("productToExchangeId", "" + ProductToExchangeId);
        return param1;
    }
    private Map<String, String> getMall2() {
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("productToExchangeId", "" + ProductToExchangeId);
        param1.put("addressId",AddressId);
        param1.put("paymentMethod", "pai");
        return param1;
    }
    private Map<String, String> getMall3() {
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("orderCode", "" + orderCode);
   //     showToast("orderCode"+orderCode);
        System.out.println("orderCode"+orderCode);
     //   param1.put("openId","");
        return param1;
    }
    /**
     * // 提交兑换积分 并支付
     */
    private void commitAndPay() {
        //使按钮无效
        btn_rear_commit.setEnabled(false);
        if (cb_wechatpay.isChecked() || cb_apipay.isChecked()) {
            getOrderCode();

        }else{
            Toast.makeText(getBaseContext(), "请选择一种支付方式", Toast.LENGTH_SHORT).show();
            // 恢复按钮功能
            btn_rear_commit.setEnabled(true);
            return;
        }
    }
    /**
     * 积分税换物品
     */
    public void getOrderCode()
    {
        tag = "ConfirmExchange_getOC";
        JSONObject jsonObject = new JSONObject(getMall2());
   //     JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://app.mlzmall.com/api/point/exchange/exchange", jsonObject, new Response.Listener<JSONObject>() {
            JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, URL.EXCHANGE.EXC, jsonObject, new Response.Listener<JSONObject>() {
//        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://app.mlzmall.com/api/point/exchange/exchange?productToExchangeId="
//                +ProductToExchangeId+"&addressId="+AddressId+"&paymentMethod=pai",
 //               jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d("积分税换物品："+jsonObject.toString());
                Gson gson = new Gson();
                ResponseExchangeInterg bean = gson.fromJson(jsonObject.toString(),ResponseExchangeInterg.class);
                orderCode = bean.getData().getOrderCode();
                LogUtils.d("orderCode:"+orderCode);
                if(cb_wechatpay.isChecked())
                {
//                    if(isWXAppInstalledAndSupported()) {
//                        showToast("已经安装");
//                        //微信支付
//                        setWeiXinPay();
//                    }else{
//                        showToast("请先进行微信安装");
//                    }
                    //微信支付
                        setWeiXinPay();
                }else if (cb_apipay.isChecked())
                {
               //     showToast("支付宝支付");
                    //支付宝支付
                    setZhiFuBaoPay();
                 //  setZhiFuBaoPay2();
                }
                btn_rear_commit.setEnabled(true);


            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }
    /**
     * 微信支付
     */
    public void setWeiXinPay()
    {
        tag = "setWeiXinPay";
        JSONObject jsonObject = new JSONObject(getMall3());
    //    JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://app.mlzmall.com/api/point/exchange/pay/wechatpay", jsonObject, new Response.Listener<JSONObject>() {
        JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST,URL.INTEGRALPAY.WECHATPAY, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d("微信支付："+jsonObject.toString());
                Gson gson = new Gson();
                ResponseWechatAppPay bean = gson.fromJson(jsonObject.toString(),ResponseWechatAppPay.class);
                //请求支付
                PayReq req = new PayReq();
                IWXAPI api = WXAPIFactory.createWXAPI(ConfirmExchangeActivity.this, null);
                // 将该app注册到微信
                api.registerApp(Constans.APP_ID);
                // 获取POST请求参数
                req.appId = bean.getData().getAppid();
                req.partnerId = bean.getData().getPartnerid();
                req.prepayId = bean.getData().getPrepayid();
                req.nonceStr = bean.getData().getNoncestr();
                req.timeStamp = bean.getData().getTimestamp();
                req.packageValue = bean.getData().getAppPackage();
                req.sign = bean.getData().getSign();
                Log.i("INFO", "发起支付中...");
                api.sendReq(req);



            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }
    /**
     * 支付宝支付
     */
    public void setZhiFuBaoPay()
    {

        tag = "setZhiFuBaoPay";
        JSONObject jsonObject = new JSONObject(getMall3());
    //    JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST, "http://app.mlzmall.com/api/point/exchange/pay/alipay", jsonObject, new Response.Listener<JSONObject>() {
            JsonRequest jsonRequest = new JsonObjectRequest(Request.Method.POST,URL.INTEGRALPAY.ALIPAY, jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                LogUtils.d("支付宝支付："+jsonObject.toString());
             //   showToast(jsonObject.toString());
                System.out.println("支付宝支付："+jsonObject.toString());
                JSONObject object1 = jsonObject.optJSONObject("data");
                String payInfo = object1.optString("payInfo");
                System.out.println("payInfo="+payInfo);
                //  构造PayTask 对象
                PayTask alipay = new PayTask(ConfirmExchangeActivity.this);
                // 调用支付接口，获取支付结果
                final String result2 = alipay.pay(payInfo);
                showToast(result2);
                Message message = handler.obtainMessage();
                message.obj = result2;
                handler.sendMessage(message);
//                AliPayResult result3 = new AliPayResult(result2);

//                if ("支付成功".equals(result3.getResult())) {
//                    startActivity(new Intent(ConfirmExchangeActivity.this, IntegralPaySuccessActivity.class));
//                    finish();
//                }
//                System.out.println("result2"+result2);
//                if ("9000".equals(result2.trim().substring(14, 18))) {
//                    startActivity(new Intent(ConfirmExchangeActivity.this, IntegralPaySuccessActivity.class));
//                    finish();
//                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(tag, error.getMessage(), error);

            }
        }) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put(ConfigInfo.CHARSET, ConfigInfo.UTF8);
                map.put(ConfigInfo.COOKIE, ConfigInfo.COOKIE_KEY + sessionId);
                map.put(ConfigInfo.TYPE, ConfigInfo.TYPE_KEY);
                return map;
            }
        };

        // 设置该请求的标签
        jsonRequest.setTag(tag);
        // 将请求添加到队列中
        ((MyApplication) getApplication()).getRequestQueue().add(jsonRequest);
    }
    public void setZhiFuBaoPay2()
    {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders requestHL = new HttpHeaders();
        requestHL.set("Cookie", "JSESSIONID=" + sessionId);
        Map map = new HashMap();
        map.put("orderCode", orderCode);
        try {
            HttpEntity requestEntityLogin = new HttpEntity<>(map, requestHL);
            String result = restTemplate.postForObject("http://app.mlzmall.com/api/point/exchange/pay/alipay", requestEntityLogin, String.class);
            JSONObject object = new JSONObject(result);
            JSONObject object1 = object.optJSONObject("data");
            String payInfo = object1.optString("payInfo");
            //  构造PayTask 对象
            PayTask alipay = new PayTask(ConfirmExchangeActivity.this);
            // 调用支付接口，获取支付结果
            String result2 = alipay.pay(payInfo);
            AliPayResult result3 = new AliPayResult(result2);
          //  showToast(result2);
            if ("支付成功".equals(result3.getResult())) {
                startActivity(new Intent(ConfirmExchangeActivity.this, IntegralPaySuccessActivity.class));
                finish();
            }

        } catch (Exception E) {
            System.out.println("alipaySDK::失败---" + E);
        }
    }
    /**
     * 判断是否安装微信
     */
    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(Constans.APP_ID);

        boolean sIsWXAppInstalledAndSupported = msgApi.isWXAppInstalled()
                && msgApi.isWXAppSupportAPI();

        return sIsWXAppInstalledAndSupported;
    }

    @Override
    public void success(int type, JSONObject jsonObject) {

    }

    @Override
    public void fail() {

    }
}
